from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Optional
from ..core.database import get_db
from .auth import get_current_user
from ..models import (
    User, File, FileType, Department,
    FolderDepartmentPermission, FolderUserPermission, ShareLevel
)
from ..schemas.permission import (
    FolderPermissionCreate, FolderPermissionInfo,
    FileShareUpdate, FileShareInfo
)

router = APIRouter()

@router.get("/folder/{folder_id}", response_model=FolderPermissionInfo)
async def get_folder_permissions(
    folder_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取文件夹权限配置"""
    folder = db.query(File).filter(
        File.id == folder_id,
        File.file_type == FileType.FOLDER,
        File.is_deleted == False
    ).first()
    
    if not folder:
        raise HTTPException(status_code=404, detail="文件夹不存在")
    
    # 检查权限：只有管理员或文件夹所有者可以查看权限
    if current_user.role.value != "admin" and folder.owner_id != current_user.id:
        raise HTTPException(status_code=403, detail="没有权限查看此文件夹权限")
    
    # 获取部门权限（包含部门信息）
    dept_permissions_query = db.query(
        FolderDepartmentPermission, Department
    ).join(
        Department, FolderDepartmentPermission.department_id == Department.id
    ).filter(
        FolderDepartmentPermission.folder_id == folder_id
    ).all()
    
    dept_permissions = []
    for perm, dept in dept_permissions_query:
        dept_permissions.append({
            "id": perm.id,
            "department_id": perm.department_id,
            "department_name": dept.name,
            "can_read": perm.can_read,
            "can_write": perm.can_write,
            "can_delete": perm.can_delete,
            "created_at": perm.created_at
        })
    
    # 获取用户权限（包含用户信息）
    user_permissions_query = db.query(
        FolderUserPermission, User
    ).join(
        User, FolderUserPermission.user_id == User.id
    ).filter(
        FolderUserPermission.folder_id == folder_id
    ).all()
    
    user_permissions = []
    for perm, user in user_permissions_query:
        user_permissions.append({
            "id": perm.id,
            "user_id": perm.user_id,
            "username": user.username,
            "full_name": user.full_name or user.username,
            "can_read": perm.can_read,
            "can_write": perm.can_write,
            "can_delete": perm.can_delete,
            "created_at": perm.created_at
        })
    
    return {
        "folder_id": folder_id,
        "folder_name": folder.name,
        "department_permissions": dept_permissions,
        "user_permissions": user_permissions
    }

@router.post("/folder/{folder_id}/department")
async def set_folder_department_permission(
    folder_id: int,
    permission_data: FolderPermissionCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """设置文件夹部门权限"""
    folder = db.query(File).filter(
        File.id == folder_id,
        File.file_type == FileType.FOLDER,
        File.is_deleted == False
    ).first()
    
    if not folder:
        raise HTTPException(status_code=404, detail="文件夹不存在")
    
    # 检查权限：只有管理员或文件夹所有者可以设置权限
    if current_user.role.value != "admin" and folder.owner_id != current_user.id:
        raise HTTPException(status_code=403, detail="没有权限设置此文件夹权限")
    
    # 检查部门是否存在
    department = db.query(Department).filter(
        Department.id == permission_data.target_id
    ).first()
    if not department:
        raise HTTPException(status_code=404, detail="部门不存在")
    
    # 检查是否已存在权限配置
    existing = db.query(FolderDepartmentPermission).filter(
        FolderDepartmentPermission.folder_id == folder_id,
        FolderDepartmentPermission.department_id == permission_data.target_id
    ).first()
    
    if existing:
        # 更新现有权限
        existing.can_read = permission_data.can_read
        existing.can_write = permission_data.can_write
        existing.can_delete = permission_data.can_delete
    else:
        # 创建新权限
        new_permission = FolderDepartmentPermission(
            folder_id=folder_id,
            department_id=permission_data.target_id,
            can_read=permission_data.can_read,
            can_write=permission_data.can_write,
            can_delete=permission_data.can_delete
        )
        db.add(new_permission)
    
    db.commit()
    return {"message": "权限设置成功"}

@router.post("/folder/{folder_id}/user")
async def set_folder_user_permission(
    folder_id: int,
    permission_data: FolderPermissionCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """设置文件夹用户权限"""
    folder = db.query(File).filter(
        File.id == folder_id,
        File.file_type == FileType.FOLDER,
        File.is_deleted == False
    ).first()
    
    if not folder:
        raise HTTPException(status_code=404, detail="文件夹不存在")
    
    # 检查权限：只有管理员或文件夹所有者可以设置权限
    if current_user.role.value != "admin" and folder.owner_id != current_user.id:
        raise HTTPException(status_code=403, detail="没有权限设置此文件夹权限")
    
    # 检查用户是否存在
    user = db.query(User).filter(User.id == permission_data.target_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 检查是否已存在权限配置
    existing = db.query(FolderUserPermission).filter(
        FolderUserPermission.folder_id == folder_id,
        FolderUserPermission.user_id == permission_data.target_id
    ).first()
    
    if existing:
        # 更新现有权限
        existing.can_read = permission_data.can_read
        existing.can_write = permission_data.can_write
        existing.can_delete = permission_data.can_delete
    else:
        # 创建新权限
        new_permission = FolderUserPermission(
            folder_id=folder_id,
            user_id=permission_data.target_id,
            can_read=permission_data.can_read,
            can_write=permission_data.can_write,
            can_delete=permission_data.can_delete
        )
        db.add(new_permission)
    
    db.commit()
    return {"message": "权限设置成功"}

@router.delete("/folder/{folder_id}/department/{department_id}")
async def remove_folder_department_permission(
    folder_id: int,
    department_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """移除文件夹部门权限"""
    folder = db.query(File).filter(
        File.id == folder_id,
        File.file_type == FileType.FOLDER,
        File.is_deleted == False
    ).first()
    
    if not folder:
        raise HTTPException(status_code=404, detail="文件夹不存在")
    
    # 检查权限：只有管理员或文件夹所有者可以移除权限
    if current_user.role.value != "admin" and folder.owner_id != current_user.id:
        raise HTTPException(status_code=403, detail="没有权限移除此文件夹权限")
    
    permission = db.query(FolderDepartmentPermission).filter(
        FolderDepartmentPermission.folder_id == folder_id,
        FolderDepartmentPermission.department_id == department_id
    ).first()
    
    if permission:
        db.delete(permission)
        db.commit()
    
    return {"message": "权限移除成功"}

@router.delete("/folder/{folder_id}/user/{user_id}")
async def remove_folder_user_permission(
    folder_id: int,
    user_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """移除文件夹用户权限"""
    folder = db.query(File).filter(
        File.id == folder_id,
        File.file_type == FileType.FOLDER,
        File.is_deleted == False
    ).first()
    
    if not folder:
        raise HTTPException(status_code=404, detail="文件夹不存在")
    
    # 检查权限：只有管理员或文件夹所有者可以移除权限
    if current_user.role.value != "admin" and folder.owner_id != current_user.id:
        raise HTTPException(status_code=403, detail="没有权限移除此文件夹权限")
    
    permission = db.query(FolderUserPermission).filter(
        FolderUserPermission.folder_id == folder_id,
        FolderUserPermission.user_id == user_id
    ).first()
    
    if permission:
        db.delete(permission)
        db.commit()
    
    return {"message": "权限移除成功"}

@router.put("/file/{file_id}/share")
async def update_file_share_level(
    file_id: int,
    share_data: FileShareUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新文件共享级别"""
    file = db.query(File).filter(
        File.id == file_id,
        File.is_deleted == False
    ).first()
    
    if not file:
        raise HTTPException(status_code=404, detail="文件不存在")
    
    # 检查权限：只有文件所有者可以设置共享级别
    if file.owner_id != current_user.id:
        raise HTTPException(status_code=403, detail="只有文件所有者可以设置共享级别")
    
    file.share_level = share_data.share_level
    db.commit()
    
    return {"message": "共享级别更新成功"}

@router.get("/file/{file_id}/share", response_model=FileShareInfo)
async def get_file_share_info(
    file_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取文件共享信息"""
    file = db.query(File).filter(
        File.id == file_id,
        File.is_deleted == False
    ).first()
    
    if not file:
        raise HTTPException(status_code=404, detail="文件不存在")
    
    # 检查权限：只有文件所有者或管理员可以查看共享信息
    if file.owner_id != current_user.id and current_user.role.value != "admin":
        raise HTTPException(status_code=403, detail="没有权限查看此文件共享信息")
    
    return FileShareInfo(
        file_id=file_id,
        file_name=file.name,
        share_level=file.share_level,
        owner_name=file.owner.full_name
    )